package cn.edu.ldu.views.main;

import cn.edu.ldu.controller.FriendController;
import cn.edu.ldu.controller.UserController;
import cn.edu.ldu.entity.FriendsEntity;
import cn.edu.ldu.protocol.Protocol;
import cn.edu.ldu.util.Consts;
import cn.edu.ldu.util.L;
import cn.edu.ldu.util.Translate;
import cn.edu.ldu.views.main.util.ListModel;
import cn.edu.ldu.views.operator.AddFriendsUI;
import cn.edu.ldu.views.operator.Friends;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 * @author DYZ
 */
public class FriendsUI extends javax.swing.JPanel {

    private String Fstr = new String();
    /**
     * Creates new form FriendsUI
     */
    public FriendsUI(int width, int height) {
        initComponents();
        this.setSize(width,height);
        this.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        leftPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listGroup = new javax.swing.JList<>();
        rightPanel = new javax.swing.JPanel();
        btnAdd = new javax.swing.JButton();
        btnDel = new javax.swing.JButton();
        btnCheck = new javax.swing.JButton();
        middlePanel = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listFriends = new javax.swing.JList<>();
        Groups = new ListModel<String>();
        member = new ListModel();

        setLayout(new java.awt.BorderLayout());

        leftPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("好友分组"));

        /*
        获取所有好友分组
        获取在线以及离线的所有好友列表
         */
        for(int i=0;i<FriendController.getFriendsList().size();i++){
            Groups.addElement(FriendController.getFriendsList().get(i).getFriendList());
        }
        listGroup.setModel(Groups);
        //双击查看好友分组中的好友
        listGroup.addMouseListener(new java.awt.event.MouseAdapter(){
            public void mouseClicked(java.awt.event.MouseEvent evt){
                btnlistGroupMouseClicked(evt);
            }
        });
//        listGroup.setModel(new javax.swing.AbstractListModel<String>() {
//            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
//            public int getSize() { return strings.length; }
//            public String getElementAt(int i) { return strings[i]; }
//        });
        jScrollPane1.setViewportView(listGroup);

        javax.swing.GroupLayout leftPanelLayout = new javax.swing.GroupLayout(leftPanel);
        leftPanel.setLayout(leftPanelLayout);
        leftPanelLayout.setHorizontalGroup(
                leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(leftPanelLayout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
        );
        leftPanelLayout.setVerticalGroup(
                leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)
        );

        add(leftPanel, java.awt.BorderLayout.LINE_START);

        btnAdd.setText("添加好友");
        btnAdd.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnAddMouseClicked(evt);
            }
        });

        btnDel.setText("删除好友");
        btnDel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnDelMouseClicked(evt);
            }
        });

        btnCheck.setText("查看好友信息");
        btnCheck.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCheckMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout rightPanelLayout = new javax.swing.GroupLayout(rightPanel);
        rightPanel.setLayout(rightPanelLayout);
        rightPanelLayout.setHorizontalGroup(
                rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(rightPanelLayout.createSequentialGroup()
                                .addGroup(rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(rightPanelLayout.createSequentialGroup()
                                                .addContainerGap()
                                                .addComponent(btnCheck))
                                        .addGroup(rightPanelLayout.createSequentialGroup()
                                                .addGap(22, 22, 22)
                                                .addGroup(rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                                        .addComponent(btnAdd)
                                                        .addComponent(btnDel))))
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        rightPanelLayout.setVerticalGroup(
                rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(rightPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(btnAdd)
                                .addGap(18, 18, 18)
                                .addComponent(btnDel)
                                .addGap(18, 18, 18)
                                .addComponent(btnCheck)
                                .addContainerGap(295, Short.MAX_VALUE))
        );

        add(rightPanel, java.awt.BorderLayout.LINE_END);

        middlePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("该分组好友"));

        listFriends.setModel(new javax.swing.AbstractListModel<String>() {
            String[] strings = { };
            public int getSize() { return strings.length; }
            public String getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(listFriends);

        javax.swing.GroupLayout middlePanelLayout = new javax.swing.GroupLayout(middlePanel);
        middlePanel.setLayout(middlePanelLayout);
        middlePanelLayout.setHorizontalGroup(
                middlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
        );
        middlePanelLayout.setVerticalGroup(
                middlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)
        );

        add(middlePanel, java.awt.BorderLayout.CENTER);
    }// </editor-fold>

    /**
     * 双击分组查看好友列表
     */
    private void btnlistGroupMouseClicked(MouseEvent evt){
        if (evt.getClickCount()==2){
            for (FriendsEntity f:FriendController.getFriendsList()){
                if (f.getFriendList().equals(listGroup.getSelectedValue())){
                    member.addElement(f.getFriendRemark(), f.getFriendId(),0);
                }
            }
            listFriends.setModel(member);
            jScrollPane2.setViewportView(listFriends);
            jScrollPane2.updateUI();
        }
    }
    /**
     * 添加好友
     * 待完成
     */
    private void btnAddMouseClicked(MouseEvent evt){
        new AddFriendsUI().setVisible(true);
    }

    /**
     * 删除好友
     * 待完成
     */
    private void btnDelMouseClicked(MouseEvent evt){

        //查看是否点击好友
        Fstr = listFriends.getSelectedValue();
        if((Fstr==null)){
            JOptionPane.showMessageDialog(null, "请选择一个好友", "标题【错误】", JOptionPane.ERROR_MESSAGE);
        }else{
            int res = JOptionPane.showConfirmDialog(null, "是否删除好友", "是否删除", JOptionPane.YES_NO_OPTION);
            if (res == JOptionPane.YES_OPTION) {
                // 点击“是”后执行这个代码块
                //提交
                try {
                    remoteAddr = InetAddress.getByName(Consts.ipv4);
                    //创建UDP套件字
                    clientSocket = new DatagramSocket();

                    //构建用户删除好友信息
                    Protocol protocol = new Protocol();
                    protocol.setKey("DeleteFriends");
                    protocol.setToken(UserController.getToken());

                    FriendsEntity friendsEntity = FriendController.getFriendsEntity(member.getUserIds(listFriends.getSelectedIndex()));

                    protocol.setData(JSON.toJSONString(friendsEntity.getId()));

                    data = Translate.ObjectToByte(protocol);

                    DatagramPacket packet = new DatagramPacket(data,data.length,remoteAddr,Consts.port);
                    clientSocket.send(packet);

                    byte[] receiveData = new byte[8096];
                    packet = new DatagramPacket(receiveData,receiveData.length,remoteAddr,Consts.port);
                    clientSocket.receive(packet);

                    L.OK(packet,FriendsUI.class);
                    Protocol pro = (Protocol) Translate.ByteToObject(packet.getData());

                    JOptionPane.showMessageDialog(this,pro.getKey(),"删除结果",JOptionPane.INFORMATION_MESSAGE);

                } catch (IOException e) {
                    e.printStackTrace();
                }
                //提交给服务器

                //提交成功
                JOptionPane.showMessageDialog(null, "删除成功", "提示", JOptionPane.YES_OPTION);

                //提交失败
            } else {
                return;
            }
        }
    }

    /**
     * 查看好友信息
     */
    private void btnCheckMouseClicked(MouseEvent evt){
        //没选中朋友
        if(listFriends.getSelectedValue() == null){
            JOptionPane.showMessageDialog(null, "请选择一个好友", "标题【错误】", JOptionPane.ERROR_MESSAGE);
        }else{
            Long FriendId = member.getUserIds(listGroup.getSelectedIndex());
            Friends friends = new Friends(FriendController.getFriendsEntity(FriendId));
            friends.setVisible(true);
        }
    }


    // Variables declaration - do not modify
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDel;
    private javax.swing.JButton btnCheck;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel leftPanel;
    private javax.swing.JList<String> listFriends;
    private javax.swing.JList<String> listGroup;
    private javax.swing.JPanel middlePanel;
    private javax.swing.JPanel rightPanel;
    private ListModel<String> Groups;
    private ListModel member;
    InetAddress remoteAddr = null;
    DatagramSocket clientSocket = null;
    private byte[] data = new byte[8096];
    // End of variables declaration
}
